package com.lanxin.xx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.xx.entity.XxDuanxiaoxi;
import com.lanxin.xx.entity.XxXiaoxijieshou;
import com.lanxin.xx.service.IXxDuanxiaoxiService;
import com.lanxin.xx.service.IXxXiaoxijieshouService;
import com.lanxin.xx.vo.Duanxiaoxi;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyq
 * @since 2025-07-26
 */
@Controller
@RequestMapping("/xx/duanxiaoxi")
public class XxDuanxiaoxiController {

    Logger logger = Logger.getLogger(XxDuanxiaoxiController.class.getName());

    @Autowired
    private IXxDuanxiaoxiService xxDuanxiaoxiService;

    @Autowired
    private IXxXiaoxijieshouService xxXiaoxijieshouService;

    @Autowired
    private IZzEmployeeService employeeService;


    /**
     * 首页展示最新内部短消息（当前用户收到的前5条）
     */
    @RequestMapping("/listRecentMsgToHome")
    public String listRecentMsgToHome(Model model, @SessionAttribute("empOid") Integer empOid) {
        // 查询当前用户收到的最新5条短消息（关联消息表获取标题）
        QueryWrapper<XxXiaoxijieshou> query = new QueryWrapper<>();
        query.eq("shoujianren", empOid) // 收件人是当前登录用户
                .orderByDesc("create_date") // 按时间倒序
                .last("limit 5");
        List<XxXiaoxijieshou> receiveList = xxXiaoxijieshouService.list(query);

        // 转换为包含消息详情的列表（使用传统for循环）
        List<Duanxiaoxi> recentMsgs = new ArrayList<>();
        for (XxXiaoxijieshou receive : receiveList) {
            // 逐个获取消息详情并添加到列表
            Duanxiaoxi msg = xxDuanxiaoxiService.getDuanxiaoxiById(receive.getXiaoxiid());
            recentMsgs.add(msg);
        }

        model.addAttribute("recentMsgs", recentMsgs); // 传递到首页
        return "home";
    }

    //去发送消息
    @RequestMapping("/toAddMsg")
    public String toAddMsg() {
        return "xx/AddMsg";
    }

    //发送消息
    @RequestMapping("/sendMsg")
    public String sendMsg(Model model,
                          XxDuanxiaoxi xxDuanxiaoxi,
                          @SessionAttribute("empOid") Integer oid,//登录的员工id
                          @RequestParam(value = "empids",required = false) String empidStr,//页面获取员工的id
                          @RequestParam(value = "file", required = false) MultipartFile file) {  // 允许为空

        String fileName = file.getOriginalFilename();
        String filePath = null;
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String savePath = "D:/duanxiaoxi/"+uuid;
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File newFile = new File(dir,fileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            filePath =uuid+"/"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Integer> empids = Arrays.stream(empidStr.split(","))//将输入字符串按逗号分隔成字符串数组 "1,2,3" → ["1", "2", "3"]
                .map(Integer::parseInt)//每个字符串元素转换为Integer类型 "1" → 1
                .collect(Collectors.toList());//将Stream流收集为List<Integer>集合

        List<XxXiaoxijieshou> xxXiaoxijieshou=new ArrayList<>();


        xxDuanxiaoxi.setCreator(oid);
        xxDuanxiaoxi.setFiles(filePath);
        xxDuanxiaoxi.setCreateDate(LocalDateTime.now());
        //xxDuanxiaoxi.setCreateDate(LocalDateTime.now().plusDays(7));//当前时间加7天

        for (Integer empid : empids) {
            XxXiaoxijieshou xiaoxi = new XxXiaoxijieshou();
            // 修复：用setShoujianren设置收件人ID（与实体类字段一致）
            xiaoxi.setJieshouren(empid);

            // 阅读状态：自己发的自己看，默认已读（Y），他人未读（N）
            if (oid.equals(empid)) {
                xiaoxi.setIsread("Y");
            } else {
                xiaoxi.setIsread("N");
            }

            xiaoxi.setXiaoxiid(xxDuanxiaoxi.getOid()); // 关联消息ID（需确保xxDuanxiaoxi已保存，oid有值）
            xxXiaoxijieshou.add(xiaoxi);
        }

//        // 先插入消息主表，获取自增的oid
//        xxDuanxiaoxiService.save(xxDuanxiaoxi);
//        Integer msgOid = xxDuanxiaoxi.getOid();
//
//        for (Integer empid : empids) {
//            XxXiaoxijieshou xiaoxi = new XxXiaoxijieshou();
//            xiaoxi.setJieshouren(empid);
//            xiaoxi.setIsread(oid.equals(empid) ? "Y" : "N");
//            xiaoxi.setXiaoxiid(msgOid); // 使用已保存的消息oid
//            xxXiaoxijieshou.add(xiaoxi);
//        }
//        xxXiaoxijieshouService.saveBatch(xxXiaoxijieshou);

        Integer row =  xxDuanxiaoxiService.sendMsg(xxDuanxiaoxi,empids);
        if(row>0){
            model.addAttribute("xxDuanxiaoxi",xxDuanxiaoxi);
        }
        return "xx/AddMsg";
    }

    //列表短消息+收件人是自己才能看
    @RequestMapping("/listMsg")
    public String listMsg(Model model,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "5") Integer pageSize,
                          @RequestParam(required = false) String biaoti,
                          @RequestParam(required = false) String empName,
                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
                          @SessionAttribute("empOid")Integer oid){

        Page<Duanxiaoxi> pageVo = new Page<>(page,pageSize);
        Page<Duanxiaoxi> listXiaoxi =  xxDuanxiaoxiService.listDuanxiaoxi(pageVo,biaoti,empName,startDate,endDate,oid);
        //查询消息接受数据，用于判断消息是否已经接受
        List<XxXiaoxijieshou> xxJieshous = xxXiaoxijieshouService.list(new QueryWrapper<XxXiaoxijieshou>().eq("jieshouren",oid));

        model.addAttribute("empOid", oid);
        model.addAttribute("listXiaoxi",listXiaoxi);
        model.addAttribute("xxJieshous",xxJieshous);
        model.addAttribute("pageVo",pageVo);
        return "xx/listInboxMsg";
    }

    //收件箱详情
    @RequestMapping("/msgInfo")
    public String msgInfo(Model model, @RequestParam Integer oid, @SessionAttribute("empOid") Integer empOid) {
        // 1. 查询消息详情（原有逻辑）
        Duanxiaoxi xiaoxi = xxDuanxiaoxiService.getDuanxiaoxiById(oid);

        if (xiaoxi == null) {
            return "xx/msgInfo";
        }

        // 2. 找到当前用户的接收记录，更新为已读（Y）
        QueryWrapper<XxXiaoxijieshou> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("xiaoxiid",xiaoxi.getOid());
        queryWrapper.eq("jieshouren",empOid);
        XxXiaoxijieshou xxXiaoxijieshou=xxXiaoxijieshouService.getOne(queryWrapper);
        xxXiaoxijieshou.setIsread("Y");
        xxXiaoxijieshouService.updateById(xxXiaoxijieshou);

        model.addAttribute("xiaoxi", xiaoxi);
        return "xx/msgInfo";
    }

    //列表已发信息+全部信息
    @RequestMapping("/showMsg")
    public String showMsg(Model model,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "5") Integer pageSize,
                          @RequestParam(required = false) String biaoti,
                          @RequestParam(required = false) String empName,
                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
                          @SessionAttribute("empOid")Integer creator){
        Page<XxDuanxiaoxi> pageVo = new Page<>(page,pageSize);
        Page<XxDuanxiaoxi> allXiaoxi =  xxDuanxiaoxiService.allMsg(pageVo,biaoti,empName,startDate,endDate,creator);
        model.addAttribute("allXiaoxi",allXiaoxi);
        model.addAttribute("pageVo",pageVo);
        return "xx/listIssuedMsg";
    }

    //已发信息详情
    @RequestMapping("/msgInfos")
    public String msgInfos(Model model,
                           @RequestParam Integer oid){
        Duanxiaoxi xiaoxi =  xxDuanxiaoxiService.getDuanxiaoxiById(oid);
        model.addAttribute("xiaoxi",xiaoxi);
        return "xx/msgInfo";
    }

}